﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SQLite;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Net.Mail;
using System.Net;

namespace MiniTennis
{
    public partial class FrmRegistroUsuario : Form
    {
        private SQLiteConnection ObjConnection;
        private SmtpClient smtpMail = new SmtpClient();
        private MailMessage msg = new MailMessage();

        private FrmInicio Inicio;

        public FrmRegistroUsuario(FrmInicio frminicio, SQLiteConnection ObjConn)
        {
            InitializeComponent();
            ObjConnection = ObjConn;
            Inicio = frminicio;
            //minitennis@tucrokis.com  3V91NBlUO2PM

            smtpMail.Credentials = new System.Net.NetworkCredential("brcp00@gmail.com", "376606210BCP");
            smtpMail.Port = 587;
            smtpMail.Host = "smtp.gmail.com";
            smtpMail.UseDefaultCredentials = false;
            smtpMail.EnableSsl = true; //Esto es para que vaya a través de SSL que es obligatorio con GMail 
            


            //smtpMail.Host = "dime155.dizinc.com";
           /* smtpMail.Host = "mail.tucrokis.com";
            smtpMail.Port = 26;
            smtpMail.EnableSsl = false;
            smtpMail.UseDefaultCredentials = false;
            smtpMail.Credentials = new NetworkCredential("minitennis@tucrokis.com", "3V91NBlUO2PM");

            */

            

        }

        private void btn_guardar_usuario_Click(object sender, EventArgs e)
        {
            //Enviar_Correo("cidarveizaga@gmail.com", "asdasd");

            if (validar())
            {
                if (!Existe_Usuario(txt_usuario.Text.Trim().ToLower()))
                {
                    String pwd = md5(DateTime.Now.Millisecond.ToString()).Substring(1,5);
                    String Sql = "INSERT INTO usuario (usu_id,usu_nombre,usu_apellido,usu_sexo,usu_fecha_nac,usu_correo,usu_password) values ('" + txt_usuario.Text.Trim().ToLower() + "','" + txt_nombre.Text.Trim()+ "','" + txt_apellido.Text.Trim() + "','" + cbx_genero.Text + "','" + GetFecha(dt_fecha_nac.Value) + "','" + txt_correo.Text.Trim().ToLower() + "','" + md5(pwd) + "')";
                    Ejecutar_consulta(Sql);
                   // Enviar_Correo(txt_correo.Text.Trim().ToLower(), pwd);
                    MessageBox.Show("El Usuario se registro correctamente, ud recibira un correo con su password, gracias!!"+ pwd);
                    this.Close();
                    Inicio.Show();
                }
                else
                {
                    MessageBox.Show("El Usuario:" + txt_usuario.Text.Trim().ToLower() + " ya existe ingrese uno nuevo por favor!");
                    this.lbl_usuario.ForeColor = Color.Red;
                }
            }
            
        }

        public void Enviar_Correo(String mail, String pwd)
        {
            try
            {
                msg.Subject = "MiniTennis";
                msg.Body = "Buenos días, \r\n \r\n el password para ingresar al juego MiniTennis es :" + pwd + ",\r\n\r\n Gracias.";
                msg.IsBodyHtml = false;
                msg.From = new MailAddress("brcp00@gmail.com");
                msg.To.Add(new MailAddress(mail));
                msg.Priority = MailPriority.Normal;
                smtpMail.Send(msg);
                msg.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        public string md5(string password)
        {
            //Declaraciones
            System.Security.Cryptography.MD5 md5;
            md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();

            //Conversion
            Byte[] encodedBytes = md5.ComputeHash(ASCIIEncoding.Default.GetBytes(password));  //genero el hash a partir de la password original

            //Resultado

            //return BitConverter.ToString(encodedBytes);      //esto, devuelve el hash con "-" cada 2 char
            return System.Text.RegularExpressions.Regex.Replace(BitConverter.ToString(encodedBytes).ToLower(), @"-", "");     //devuelve el hash continuo y en minuscula. (igual que en php)
        }

        public Boolean Existe_Usuario(String usu)
        {
            String Sql = "select usu_id from usuario where usu_id = '" + usu + "'";  
            SQLiteCommand ObjCommand = new SQLiteCommand(Sql, ObjConnection);
            ObjCommand.CommandType = CommandType.Text;
            SQLiteDataAdapter ObjDataAdapter = new SQLiteDataAdapter(ObjCommand);
            DataSet dataSet = new DataSet();

            ObjDataAdapter.Fill(dataSet, "consultoras");

            if (dataSet.Tables["consultoras"].Rows.Count > 0)
                return true;
            else
                return false;         
           
        }

        public Boolean validar()
        {
            Boolean sw = true;

            if (txt_nombre.Text.Trim().Length == 0)
            {
                lbl_nombre.ForeColor = Color.Red;
                sw = false;
            }
            else
                lbl_nombre.ForeColor = Color.Black;  

            if (txt_apellido.Text.Trim().Length == 0)
            {
                lbl_apellido.ForeColor = Color.Red;
                sw = false;
            }
            else
                lbl_apellido.ForeColor = Color.Black; 

            if (txt_usuario.Text.Trim().Length == 0)
            {
                lbl_usuario.ForeColor = Color.Red;
                sw = false;
            }
            else
                lbl_usuario.ForeColor = Color.Black;


            if (cbx_genero.Text.Trim().Length == 0)
            {
                lbl_sexo.ForeColor = Color.Red;
                sw = false;
            }
            else
                lbl_sexo.ForeColor = Color.Black;



            if (txt_correo.Text.Trim().Length == 0)
            {
                lbl_correo.ForeColor = Color.Red;
                sw = false;
            }
            else
            {
                if (!email_bien_escrito(txt_correo.Text.Trim().ToLower()))
                {                    
                    lbl_error_correo.ForeColor = Color.Red;
                    lbl_error_correo.Visible = true;

                    sw = false;
                }
                else
                {
                    lbl_correo.ForeColor = Color.Black;
                    lbl_error_correo.Visible = false;
                }
            }
            return sw;
        }

        private Boolean email_bien_escrito(String email)
        {
            String expresion;
            expresion = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
            if (Regex.IsMatch(email, expresion))
            {
                if (Regex.Replace(email, expresion, String.Empty).Length == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public String GetFecha(DateTime dia)
        {
            String strDia = "";
            strDia = (Convert.ToString(dia.Day).Length == 1 ? "0" + Convert.ToString(dia.Day) : Convert.ToString(dia.Day)) + "/" + (Convert.ToString(dia.Month).Length == 1 ? "0" + Convert.ToString(dia.Month) : Convert.ToString(dia.Month)) + "/" + Convert.ToString(dia.Year);
            return strDia;
        }

        private void Ejecutar_consulta(string txtQuery)
        {
            ObjConnection.Open();
            SQLiteCommand ObjCommand = new SQLiteCommand(ObjConnection);
            ObjCommand.CommandText = txtQuery;
            ObjCommand.ExecuteNonQuery();
            ObjConnection.Close();
        }

        private void btn_cancelar_Click(object sender, EventArgs e)
        {
            this.Close();
            Inicio.Show();
        }
    }
}
